package znet

import (
	"errors"
	"fmt"
	"net"
	ziface "zinx/Ziface"
)

// IServer的接口实现
type Server struct {
	Name      string //服务器名称
	IPVersion string
	IP        string
	port      int
}

//回显业务
func CallBackToClient(conn *net.TCPConn,data []byte ,cnt int) error{
	fmt.Println("[ Conn Handler callbacktoClient ]....")
	if _,err:=conn.Write(data[:cnt]);err!=nil{
		fmt.Println(" write callback err: ",err)
		return errors.New("CallBackToClient err") //自己创建一个错误
	}
	return nil
}




// 启动服务器
func (s *Server) Start() {
	//获取一个TCP的addr
	fmt.Printf("[Start] Server Listenner at IP:%s,Port:%d is starting\n", s.IP, s.port)
	addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP, s.port))
	if err != nil {
		fmt.Println("resolve tcp addt error: ", err)
		return
	}
	go func() {
		//listen
		listener, err := net.ListenTCP(s.IPVersion, addr)
		if err != nil {
			fmt.Println("listen tcp error: ", err)
			return
		}

		fmt.Println("start Zinx server sucess:", s.Name, "sucess Listenning...")
		var connid uint32
		connid=0
		//accept
		for {
			conn, err := listener.AcceptTCP()
			if err != nil {
				fmt.Println("Accept err", err)
				continue
			}
			connid++
			//提取一个链接，就创建一个Connection
			dealconn:=NewConnection(conn,connid,CallBackToClient)
			go dealconn.Start()
		}
	}()

}



// 停止服务器
func (s *Server) Stop() {
	//回收资源
}

// 运行服务器
func (s *Server) Serve() {
	s.Start()
	//设置为阻塞状态,防止主线程结束，导致s.Start协程介绍
	select {}
}

/*
	初始化Server模块的方法
*/

func NewServer(name string) ziface.IServer {
	s := &Server{
		Name:      name,
		IPVersion: "tcp4",
		IP:        "0.0.0.0",
		port:      8999,
	}

	return s
}
